<template>
  <dv-border-box-12 class="center">
    <div class="d-flex" style="margin-left:10px">
      <span><i class="iconfont icon-align-left"></i></span>
      <span class="fs-xl text mx-2 mt-1" style="font-size:19px;color: #eaedf3;">{{ title }}</span>
    </div>
    <dv-capsule-chart
      :config="config"
      id="bar-chart"
    />
  </dv-border-box-12>
</template>

<script>
import { defineComponent, reactive, watch } from "vue";
export default defineComponent({
  props: {
    title: {
      type: String,
      default: "",
    },
    statistics: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const config = reactive({
      data: [],
      rowNum: 5,
      showValue: true,
      // 确保图表有默认颜色配置
      color: ['#568aea', '#50e3c2', '#67a1e5', '#ff7d00', '#00c1d4']
    });

    // 监听statistics变化并标准化数据格式
    watch(
      () => props.statistics,
      (newVal) => {
        // 数据标准化处理
        if (Array.isArray(newVal)) {
          config.data = newVal
            .filter(item => item && item.name && item.value !== undefined) // 过滤无效数据
            .map(item => ({
              name: String(item.name), // 确保name为字符串
              value: Number(item.value) || 0 // 确保value为数字且非NaN
            }));
        } else {
          config.data = []; // 非数组数据置空
        }
        console.log(`[${props.title}] 图表数据:`, config.data); // 调试日志
      },
      { immediate: true }
    );

    return { config };
  },
});
</script>

<style lang="scss" scoped>
.center {
  display: flex;
  flex-direction: column;
  height: 350px; /* 固定高度避免容器塌陷 */
  min-height: 350px;
  margin: 10px; /* 增加间距避免重叠 */
  
  .d-flex {
    margin-top: 4%;
  }
  
  #bar-chart {
    font-size: 16px; /* 调整字体大小适配 */
    width: 95%;
    height: calc(100% - 40px); /* 动态计算高度 */
    margin: 0 auto;
  }
}
</style>